import 'dart:convert';

import 'package:app_settings/app_settings.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:top_foundation/component/dialog/index.dart';
import 'package:regular_assess/helper/global/user/logic.dart';
import 'package:regular_assess/helper/utils/ifly/ifly_util.dart';

import '../../helper/utils/util.dart';
import 'index.dart';

class WebController extends GetxController {
  WebController();

  final state = WebViewState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    super.onInit();
    state.url = Get.parameters['url'];
    state.title = Get.parameters['title'];
    state.isSafeArea = Get.parameters['safeArea'] == '1';
    state.isHostPage = Get.parameters['isHost'] == '1';
  }

  void onRecord() async {
    if (!await getPermisson()) {
      // Hud.toast('请前往设置打开麦克风权限');
      showAlert(
        msg: '请前往设置打开麦克风权限',
      ).then((value) {
        if (value == 1) {
          AppSettings.openAppSettings(type: AppSettingsType.settings);
        }
      });
      return;
    }
    state.webCtrl!.evaluateJavascript(source: 'startRecorderSuccess()');
    var res = await IFlyUtil().ifly_audio();
    state.webCtrl!
        .evaluateJavascript(source: 'endRecorder(${jsonEncode(res.json)})');
  }

  void getUser() {
    var json = jsonEncode(UserController.instance.state.user!.toJson());
    Get.log("resUser--\n$json");
    state.webCtrl!.evaluateJavascript(source: "resUser($json)");
  }

  void logOut() {
    UserController.instance.loginOutSuccess();
    Get.offAllNamed(RouterPath.login);
  }

  void pageFinished() async {
    var url = await state.webCtrl!.getUrl();
    var isWebCanBack =
        !(url!.path.endsWith("#/login") || url.path.endsWith("#/home"));
    if (state.isWebCanBack != isWebCanBack) {
      state.isWebCanBack = isWebCanBack;
      update();
    }
  }

  Future<bool> getPermisson() async {
    var isGranted = await Permission.microphone.isGranted;
    if (!isGranted) {
      var res = await [
        Permission.microphone,
      ].request();
      if (res[Permission.microphone] == PermissionStatus.granted) {
        return true;
      }
      return false;
    }

    return true;
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
